const { verifyToken } = require('../utils/jwt');

const authMiddleware = async (ctx, next) => {
  const token = ctx.headers.authorization?.split(' ')[1];
  
  if (!token) {
    ctx.status = 401;
    ctx.body = { message: '拒绝访问。未提供令牌 --- Access denied. No token provided.' };
    return;
  }
  
  try {
    const decoded = verifyToken(token);
    // 确保ctx.state.user包含userId字段，与token中的id字段对应
    ctx.state.user = {
      userId: decoded.id,
      username: decoded.username,
      role: decoded.role // 添加角色信息
    };
    await next();
  } catch (error) {
    ctx.status = 401;
    ctx.body = { message: '无效令牌 --- Invalid token.' };
  }
};

module.exports = authMiddleware;
